﻿using System;

namespace RexToy.UI.Controls
{
    public class VChoiceGroup : ChoiceGroup
    {
        public VChoiceGroup(bool allowMulti)
            : base(allowMulti)
        {
            this.__domNode = RexToy.UI.Controls.DomNode.Create(new DomNodeCreateOptions()
            {
                tag = Tag.Div,
                hashName = "container",
                className = "ui-controlgroup-vertical"
            });
        }

        public override void AppendChoice(string text, object value)
        {
            Control ctrl;
            if (this._multi)
            {
                ctrl = new RexToy.UI.Controls.CheckBox(text, value, true);
            }
            else
            {
                ctrl = new RexToy.UI.Controls.RadioButton(text, value, true);
            }

            ctrl.AttachEvent("onchange", new Action<object>(this.OnChange).Bind(this));
            this.AppendControl(ctrl);
        }

        public override void RemoveChoice(object value)
        {
            for (var i = 0; i < this.__controls.Length; i++)
            {
                var ch = this.__controls[i] as IChoiceControl;
                if (ch.Value == value)
                {
                    this.RemoveControl(ch as Control);
                    break;
                }
            }
        }

        public override void ClearChoice()
        {
            this.ClearControls();
        }

        private void OnChange(object sender)
        {
            if (!this._multi)
            {
                foreach (IChoiceControl ctrl in __controls)
                {
                    if (ctrl != sender)
                        ctrl.Checked = false;
                }
            }
            this.__FireEvent("onchange");
        }
    }
}
